import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, In, IsNull, Not, Repository, UpdateResult } from 'typeorm';
import { Agent } from './entities/agent.entity';
import { FollowUp } from './entities/follow-up.entity';
import { User } from '../users/entities/user.entity';
import { isNotEmpty } from 'class-validator';
import { Approval } from './entities/approval.entity';

@Injectable()
export class AgentsService {
  constructor(
    @InjectRepository(Agent)
    private agentsRepository: Repository<Agent>,
    @InjectRepository(FollowUp)
    private followUpsRepository: Repository<FollowUp>,
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    @InjectRepository(Approval)
    private approvalsRepository: Repository<Approval>,
  ) { }

  // 获取所有代理商
  async findAll(): Promise<Agent[]> {
    return this.agentsRepository.find({
      relations: ['assignedTo', 'followUps'],
    });
  }

  // 获取公共池
  async findUnassigned(): Promise<Agent[]> {
    return this.agentsRepository.find({
      relations: ['assignedTo', 'followUps', 'lastAssignedTo'],
      where: {
        status: 'active',
        assignedTo: IsNull()
      },
    });
  }

  // 获取已分配
  async findAssigned(user): Promise<Agent[]> {
    const { id, role } = user;
    if (role === 0) {
      // manager可以看所有
      return this.agentsRepository.find({
        relations: ['assignedTo', 'followUps'],
        where: {
          status: 'active',
          assignedTo: Not(IsNull())
        },
      });
    } else if (role === 1) {
      const findUser = await this.usersRepository.findOne({
        where: {
          id,
        },
        relations: ['subordinates'],
      });
      if (findUser) {
        const { subordinates } = findUser;
        const findSubUserAgent = await this.agentsRepository.find({
          relations: ['assignedTo'],
          where: {
            status: 'active',
            assignedTo: {
              id: In([...subordinates, findUser].map(user => user.id))
            }
          }
        })
        return findSubUserAgent;
      }
    }
    return this.agentsRepository.find({
      relations: ['assignedTo', 'followUps'],
      where: {
        status: 'active',
        assignedTo: {
          id
        }
      },
    });
  }

  // 获取我的代理商
  async findMyAgents(userId: number): Promise<Agent[]> {
    return this.agentsRepository.find({
      // where: { assignedTo: userId },
      relations: ['assignedTo', 'followUps'],
    });
  }

  // 获取单个代理商
  async findOne(id: number): Promise<Agent> {
    const agent = await this.agentsRepository.findOne({
      where: { id, status: 'active' },
      relations: ['assignedTo', 'followUps'],
    });
    if (!agent) {
      throw new NotFoundException(`代理商 #${id} 不存在`);
    }
    return agent;
  }

  // 创建代理商
  async create(createAgentDto: any): Promise<Agent> {
    const agent = this.agentsRepository.create(createAgentDto);
    return this.agentsRepository.save(agent)[0];
  }

  // 更新代理商
  async update(id: number, updateAgentDto: any): Promise<Agent> {
    await this.agentsRepository.update(id, updateAgentDto);
    return this.findOne(id);
  }

  // 删除代理商
  async remove(id: number): Promise<void> {
    const agent = await this.findOne(id);
    agent.status = 'inactive';
    this.agentsRepository.save(agent)
    return
  }

  // 分配代理商
  async assign(id: number, userId: number): Promise<Agent> {
    const agent = await this.findOne(id);
    const user = await this.usersRepository.findOne({ where: { id: userId } });
    agent.assignedTo = user || null;
    return this.agentsRepository.save(agent);
  }

  // 退回公共池
  async returnToPool(id: number): Promise<Agent> {
    const agent = await this.findOne(id);
    agent.assignedTo = null;
    return this.agentsRepository.save(agent);
  }

  // 添加跟进记录
  async addFollowUp(id: number, userId: number, updateInfo: any): Promise<FollowUp[]> {
    const agent = await this.findOne(id);
    const followUp = this.followUpsRepository.create({
      ...updateInfo,
      agent,
      createdBy: { id: userId },
    });
    return this.followUpsRepository.save(followUp);
  }

  // 更新跟进记录
  async updateFollowUp(id: number, userId: number, updateInfo: any): Promise<FollowUp[]> {
    await this.followUpsRepository.update(id, {
      ...updateInfo,
      updatedBy: {
        id: userId
      },
    });
    return this.followUpsRepository.find({
      where: {
        id,
      }
    });
  }

  async getFollowUps(id: number) {
    return this.followUpsRepository.find({
      where: { agent: { id }, status: 'active' },
      relations: ['createdBy', 'updatedBy', 'approvals', 'approvals.createdBy'],
      order: {
        createdAt: 'DESC',
        approvals: {     // 关联实体排序
          createdAt: 'DESC' // posts按创建时间降序
        }
      },
    });
  }

  async deleteFollowUps(id: number): Promise<UpdateResult> {
    return await this.followUpsRepository.update(id, {
      status: 'inactive',
    });
  }

  async isSubordinate(userId: number, supervisorId: number): Promise<boolean> {
    const user = await this.usersRepository.findOne({
      where: { id: userId },
      relations: ['supervisor'],
    });
    return user?.id === supervisorId;
  }

  // 添加跟进记录
  async addFollowUpApproval(id: number, userId: number, updateInfo: any): Promise<Approval[]> {
    const approval = this.approvalsRepository.create({
      ...updateInfo,
      followUp: {
        id,
      },
      createdBy: { id: userId },
    });
    return this.approvalsRepository.save(approval);
  }
} 